package com.liuhongwei.test.builder;

import com.liuhongwei.test.bean.Constants;
import com.liuhongwei.test.bean.FieldInfo;
import com.liuhongwei.test.bean.TableInfo;
import com.liuhongwei.test.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.Map;


public class BuildController {

    private static final Logger log = LoggerFactory.getLogger(BuildController.class);


    public static void execute(TableInfo tableInfo) {
        File folder = new File(Constants.PATH_CONTROLLER);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        OutputStream os = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        try {
            String beanName = tableInfo.getBeanName();
            String beanParamName = tableInfo.getBeanParamName();
            String className = beanName + "Controller";
            String serviceName = beanName + "Service";

            os = new FileOutputStream(folder + "/" + className + ".java");
            osw = new OutputStreamWriter(os, "UTF-8");
            bw = new BufferedWriter(osw);

            bw.write("package " + Constants.PACKAGE_CONTROLLER + ";\n\n");
            //写入Import
            writeImport(bw, beanName, beanParamName, serviceName);
            //写入类注释
            BuildComment.createClassComment(bw, tableInfo.getComment() + "Controller");
            bw.write("@RestController\n");
            bw.write("@RequestMapping(\"/" + StringUtils.lowerCaseFirst(beanName) + "/\")\n");
            bw.write("public class " + className + " {\n\n");

            //写入属性
            writeField(tableInfo, bw, beanName, beanParamName, serviceName);

            bw.write("}");
            bw.flush();
        } catch (Exception e) {
            log.error("创建Service失败", e);
        } finally {
            BuildBase.close(os, osw, bw);
        }
    }


    private static void writeField(TableInfo tableInfo, BufferedWriter bw, String beanName, String beanParamName,
            String serviceName) throws Exception {
        String serviceBeanName = StringUtils.lowerCaseFirst(serviceName);

        bw.write("\t@Resource\n");
        bw.write("\tprivate " + serviceName + " " + serviceBeanName + ";\n\n");

        BuildComment.createFieldComment(bw, "页面分页查询");
        bw.write("\t@PostMapping(value = \"/list\", produces = {\"application/json;charset=UTF-8\"})\n");
        bw.write("\tpublic JSONResponse getPage(@RequestBody JSONRequest jsonRequest) {\n");
        bw.write(String.format("\t\treturn %s.getPage(jsonRequest);\n", serviceBeanName));
        bw.write("\t}\n\n");

        BuildComment.createFieldComment(bw, "页面新增");
        bw.write("\t@PostMapping(value = \"/add\", produces = {\"application/json;charset=UTF-8\"})\n");
        bw.write("\tpublic JSONResponse add(@RequestBody JSONRequest jsonRequest) {\n");
        bw.write(String.format("\t\treturn %s.add(jsonRequest);\n", serviceBeanName));

        bw.write("\t}\n\n");

        BuildComment.createFieldComment(bw, "页面更新");
        bw.write("\t@PostMapping(value = \"/update\", produces = {\"application/json;charset=UTF-8\"})\n");
        bw.write("\tpublic JSONResponse update(@RequestBody JSONRequest jsonRequest) {\n");
        bw.write(String.format("\t\treturn %s.update(jsonRequest);\n", serviceBeanName));

        bw.write("\t}\n\n");

        BuildComment.createFieldComment(bw, "页面删除");
        bw.write("\t@PostMapping(value = \"/delete\", produces = {\"application/json;charset=UTF-8\"})\n");
        bw.write("\tpublic JSONResponse delete(@RequestBody JSONRequest jsonRequest) {\n");
        bw.write(String.format("\t\treturn %s.delete(jsonRequest);\n", serviceBeanName));

        bw.write("\t}\n\n");

        BuildComment.createFieldComment(bw, "页面详情");
        bw.write("\t@PostMapping(value = \"/get\", produces = {\"application/json;charset=UTF-8\"})\n");
        bw.write("\tpublic JSONResponse get(@RequestBody JSONRequest jsonRequest) {\n");
        bw.write(String.format("\t\treturn %s.get(jsonRequest);\n", serviceBeanName));

        bw.write("\t}\n\n");

//        writeFieldDynamic(tableInfo, bw, beanName, serviceBeanName);
    }

    private static void writeFieldDynamic(TableInfo tableInfo, BufferedWriter bw, String beanName,
            String serviceBeanName) throws IOException {
        Map<String, List<FieldInfo>> keyIndexMap = tableInfo.getKeyIndexMap();
        for (Map.Entry<String, List<FieldInfo>> entry : keyIndexMap.entrySet()) {
            List<FieldInfo> fieldInfoList = entry.getValue();

            Integer index = 0;
            StringBuilder methodName = new StringBuilder();
            StringBuilder methodParam = new StringBuilder();
            StringBuilder methodField = new StringBuilder();
            for (FieldInfo fieldInfo : fieldInfoList) {
                index++;
                String propertyName = fieldInfo.getPropertyName();
                methodName.append(StringUtils.upperCaseFirst(propertyName));
                methodParam.append(fieldInfo.getJavaType() + " " + propertyName);
                methodField.append(propertyName);
                if (index < fieldInfoList.size()) {
                    methodName.append("And");
                    methodParam.append(", ");
                    methodField.append(", ");
                }
            }
            BuildComment.createFieldComment(bw, "根据" + methodName + "查询");
            String selectMethodName = "selectBy" + methodName;
            bw.write("\t@RequestMapping(\"" + selectMethodName + "\")\n");
            bw.write("\tpublic ResponseVO " + selectMethodName + "(" + methodParam + ") {\n");
            bw.write("\t\treturn getSuccessResponseVO(" + serviceBeanName + "." + selectMethodName + "(" + methodField
                    + "));\n");
            bw.write("\t}\n\n");

            BuildComment.createFieldComment(bw, "根据" + methodName + "更新");
            String updateMethodName = "updateBy" + methodName;
            bw.write("\t@RequestMapping(\"" + updateMethodName + "\")\n");
            bw.write("\tpublic ResponseVO " + updateMethodName + "(" + beanName + " bean, " + methodParam + ") {\n");
            bw.write("\t\t" + serviceBeanName + "." + updateMethodName + "(bean, " + methodField + ");\n");
            bw.write("\t\treturn getSuccessResponseVO(null);\n");
            bw.write("\t}\n\n");

            BuildComment.createFieldComment(bw, "根据" + methodName + "删除");
            String deleteMethodName = "deleteBy" + methodName;
            bw.write("\t@RequestMapping(\"" + deleteMethodName + "\")\n");
            bw.write("\tpublic ResponseVO " + deleteMethodName + "(" + methodParam + ") {\n");
            bw.write("\t\t" + serviceBeanName + "." + deleteMethodName + "(" + methodField + ");\n");
            bw.write("\t\treturn getSuccessResponseVO(null);\n");
            bw.write("\t}\n\n");
        }
    }

    private static void writeImport(BufferedWriter bw, String beanName, String beanParamName, String serviceName)
            throws IOException {
        bw.write("import javax.annotation.Resource;\n");
        bw.write("import org.springframework.web.bind.annotation.RequestBody;\n");
        bw.write("import org.springframework.web.bind.annotation.RequestMapping;\n");
        bw.write("import org.springframework.web.bind.annotation.RestController;\n");
        bw.write("import org.springframework.web.bind.annotation.PostMapping;\n");
        bw.write("import com.alibaba.fastjson.JSONObject;\n");
        bw.write("import com.liuhongwei.test.entity.vo.JSONRequest;\n");
        bw.write("import com.liuhongwei.test.entity.vo.JSONResponse;\n");
        bw.write("import " + Constants.PACKAGE_SERVICE + "." + serviceName + ";\n\n");
    }


    public static void main(String[] args) {
        List<TableInfo> tableInfoList = BuildTable.getTable();
        for (TableInfo tableInfo : tableInfoList) {
            BuildController.execute(tableInfo);
        }
    }

}
